// Copyright (c) 2009 Alistair Jones
// This program is made available under the terms of the MIT License.
package org.hypirinha.html.codegen;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;

public class SchemaParser {

    public Document parseSchema() {
        return parse(getClass().getResourceAsStream("xhtml1-transitional.xsd"));
    }

    public Document parse(String string) {
        return parse(new ByteArrayInputStream(string.getBytes()));
    }

    private Document parse(InputStream stream) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            return documentBuilder.parse(stream);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
    }
}
